package com.qilu.pe.ui.activity;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.listener.OnTimeSelectChangeListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.contrarywind.interfaces.IPickerViewData;
import com.qilu.pe.R;
import com.qilu.pe.base.Base2Activity;
import com.qilu.pe.base.BaseResult2;
import com.qilu.pe.base.Config;
import com.qilu.pe.base.Global;
import com.qilu.pe.dao.bean.AgentFlow;
import com.qilu.pe.dao.bean.Doctor;
import com.qilu.pe.dao.http.APIRetrofit;
import com.qilu.pe.support.util.ActiviceCollector;
import com.qilu.pe.support.util.PeUtil;
import com.ruitu.arad.api.RxUtil;
import com.ruitu.arad.base.base_list.ListBaseAdapter;
import com.ruitu.arad.base.base_list.SuperViewHolder;
import com.ruitu.arad.util.ToastUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

// 机构流水
public class AgentFlowActivity extends Base2Activity {
    private RecyclerView rcv_flow;
    private TextView tv_choose_doctor, tv_pay_type, tv_start_time, tv_end_time;
    private TextView tv_search;// 搜索
    private TextView empty_view;

    private AgentFlowAdapter adapter;
    private List<AgentFlow> flowList = new ArrayList<>();

    private ArrayList<Doctor> doctorList = new ArrayList<>();// 传过来的我的机构医生列表
    private Doctor currDoctor;// 当前选择的医生

    private String expert;// 当前选择的医生id
    private String payType;// 选择的支付类型 支付类型（1 微信,2 支付宝,3 银联支付,4 余额支付）
    private String startDate;// 开始日期
    private String endDate;// 结束日期

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_agent_flow;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActiviceCollector.addActivity(this);
        rcv_flow = findViewById(R.id.rcv_flow);
        tv_choose_doctor = findViewById(R.id.tv_choose_doctor);
        tv_pay_type = findViewById(R.id.tv_pay_type);
        tv_start_time = findViewById(R.id.tv_start_time);
        tv_end_time = findViewById(R.id.tv_end_time);
        tv_search = findViewById(R.id.tv_search);
        empty_view = findViewById(R.id.empty_view);

        Bundle bundle = getIntent().getExtras();
        if (null != bundle) {
            doctorList = (ArrayList<Doctor>) bundle.getSerializable("doctorList");
        }

        setHeadTitle("机构流水");

        LinearLayoutManager manager = new LinearLayoutManager(this);
        adapter = new AgentFlowAdapter(this);
        rcv_flow.setLayoutManager(manager);
        rcv_flow.setAdapter(adapter);

        setListeners();

        hideProgress();
        reqAgentFlowList();
        hideProgress();
    }

    private void setListeners() {
        setOnClickListener(tv_choose_doctor, tv_pay_type, tv_start_time, tv_end_time, tv_search);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v == tv_choose_doctor) {// 选择医生
            initCustomOptionPicker();
            pvCustomOptions.show();
        }
        if (v == tv_pay_type) {// 支付类型
            initCustomOptionPicker2();
            pvCustomOptions2.show();
        }
        if (v == tv_search) {// 搜索
            hideProgress();
            reqAgentFlowList();
            showProgress();
        }
        if (v == tv_start_time) {// 支付日期起
            dateType = 1;
            initDatePicker();
            pvTime.show();
        }
        if (v == tv_end_time) {// 支付日期结束
            dateType = 2;
            initDatePicker();
            pvTime.show();
        }
    }

    private TimePickerView pvTime;
    private int dateType = 1;// 日期选择器的类型 1 开始日期 2 结束日期

    private void initDatePicker() {//Dialog 模式下，在底部弹出
        pvTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                if (dateType == 1) {// 开始日期
                    startDate = getTime(date);
                    tv_start_time.setText(startDate);
                } else {// 结束日期
                    endDate = getTime(date);
                    tv_end_time.setText(endDate);
                }
            }
        }).setTimeSelectChangeListener(new OnTimeSelectChangeListener() {
            @Override
            public void onTimeSelectChanged(Date date) {
            }
        }).setType(new boolean[]{true, true, true, false, false, false})
                .isDialog(true) // 默认设置false ，内部实现将DecorView 作为它的父控件。
                .addOnCancelClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                    }
                })
                .setItemVisibleCount(7) //若设置偶数，实际值会加1（比如设置6，则最大可见条目为7）
                .setLineSpacingMultiplier(2.0f)
                .isAlphaGradient(true)
                .setTitleText("选择日期")
                .build();

        Dialog mDialog = pvTime.getDialog();
        if (mDialog != null) {
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.BOTTOM);
            params.leftMargin = 0;
            params.rightMargin = 0;
            pvTime.getDialogContainerLayout().setLayoutParams(params);

            Window dialogWindow = mDialog.getWindow();
            if (dialogWindow != null) {
                dialogWindow.setWindowAnimations(com.bigkoo.pickerview.R.style.picker_view_slide_anim);//修改动画样式
                dialogWindow.setGravity(Gravity.BOTTOM);//改成Bottom,底部显示
                dialogWindow.setDimAmount(0.3f);
            }
        }
    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
        if (dateType == 1) {// 开始日期
            SimpleDateFormat format = new SimpleDateFormat(Config.TIME_FORMATE_YMD);
            return format.format(date);
        } else {// 结束日期
            SimpleDateFormat format = new SimpleDateFormat(Config.TIME_FORMATE_YMD);
            return format.format(date);
        }
    }

    private Disposable reqAgentFlowList() {
        return APIRetrofit.getDefault().reqAgentFlowList(Global.HEADER, 1, 999999, Global.ORG_ID, expert, payType)
                .compose(RxUtil.<BaseResult2<List<AgentFlow>>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<AgentFlow>>>() {
                    @Override
                    public void accept(BaseResult2<List<AgentFlow>> listBaseResult2) throws Exception {
                        hideProgress();
                        if (listBaseResult2.isSuccess()) {
                            flowList = listBaseResult2.getData();
                            adapter.setDataList(flowList);
                        } else {
                            ToastUtils.showShort(listBaseResult2.getMsg());
                        }
                        if (isDataEmpty(flowList)) {
                            empty_view.setVisibility(View.VISIBLE);
                        } else {
                            empty_view.setVisibility(View.GONE);
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        empty_view.setVisibility(View.VISIBLE);
                    }
                });
    }

    private ArrayList<Doctor> typeList = new ArrayList<>();// 支付类型（1 微信,2 支付宝,3 银联支付,4 余额支付）

    private OptionsPickerView pvCustomOptions;// 条件选择器

    /**
     * @description 注意事项：自定义布局中，id为 optionspicker 或者 timepicker 的布局以及其子控件必须要有，否则会报空指针。
     * 具体可参考demo 里面的两个自定义layout布局。
     */
    private void initCustomOptionPicker() {//条件选择器初始化，自定义布局
        pvCustomOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = typeList.get(options1).getPickerViewText();
                tv_choose_doctor.setText(tx);
                currDoctor = typeList.get(options1);
                expert = currDoctor.getId();
            }
        }).setLayoutRes(R.layout.pickerview_custom_options, new CustomListener() {
            @Override
            public void customLayout(View v) {
                final TextView tvSubmit = v.findViewById(R.id.tv_finish);
                ImageView ivCancel = v.findViewById(R.id.iv_cancel);
                tvSubmit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        pvCustomOptions.returnData();
                        pvCustomOptions.dismiss();
                    }
                });

                ivCancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        pvCustomOptions.dismiss();
                    }
                });
            }
        })
                .isDialog(true)
                .setOutSideCancelable(false)
                .build();

        typeList = doctorList;// 生成数据
        pvCustomOptions.setPicker(typeList);// 设置数据
    }

    private ArrayList<CardBean> payTypeList = new ArrayList<>();

    private OptionsPickerView pvCustomOptions2;// 支付类型条件选择器

    private void initCustomOptionPicker2() {// 支付类型条件选择器初始化，自定义布局
        pvCustomOptions2 = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = payTypeList.get(options1).getPickerViewText();
                payType = "" + payTypeList.get(options1).getId();
                tv_pay_type.setText(tx);
            }
        }).setLayoutRes(R.layout.pickerview_custom_options, new CustomListener() {
            @Override
            public void customLayout(View v) {
                final TextView tvSubmit = v.findViewById(R.id.tv_finish);
                ImageView ivCancel = v.findViewById(R.id.iv_cancel);
                tvSubmit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        pvCustomOptions2.returnData();
                        pvCustomOptions2.dismiss();
                    }
                });

                ivCancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        pvCustomOptions2.dismiss();
                    }
                });
            }
        })
                .isDialog(true)
                .setOutSideCancelable(false)
                .build();

        getCardData();// 生成数据
        pvCustomOptions2.setPicker(payTypeList);// 设置数据
    }

    private void getCardData() {
        payTypeList.clear();
        // 支付类型（1 微信,2 支付宝,3 银联支付,4 余额支付）
        payTypeList.add(new CardBean(1, "微信"));
        payTypeList.add(new CardBean(2, "支付宝"));
        payTypeList.add(new CardBean(3, "银联支付"));
        payTypeList.add(new CardBean(4, "余额支付"));
    }

    // 机构类型(选项前端写死 1 综合性医院 2 社区卫生服务中心 3 门诊部/诊所/卫生所/医务室/村卫生室 4 采供血机构)
    public class CardBean implements IPickerViewData {
        int id;
        String cardNo;

        public CardBean(int id, String cardNo) {
            this.id = id;
            this.cardNo = cardNo;
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getCardNo() {
            return cardNo;
        }

        public void setCardNo(String cardNo) {
            this.cardNo = cardNo;
        }

        @Override
        public String getPickerViewText() {
            return cardNo;
        }
    }

    private class AgentFlowAdapter extends ListBaseAdapter<AgentFlow> {

        public AgentFlowAdapter(Context context) {
            super(context);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_agent_flow_list;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, int position) {
            TextView tv_name = holder.getView(R.id.tv_name);
            TextView tv_time = holder.getView(R.id.tv_time);
            TextView tv_pay_type = holder.getView(R.id.tv_pay_type);
            TextView tv_money_num = holder.getView(R.id.tv_money_num);

            AgentFlow flow = mDataList.get(position);
            tv_name.setText(TextUtils.isEmpty(flow.getSalesman()) ? "无" : flow.getSalesman());
            tv_time.setText(flow.getCreated_at());
            tv_pay_type.setText(PeUtil.getAgentFlowType(flow.getType()));

//            String flowType = TextUtils.equals("0", flow.getPay_type()) ? "-" : "+";// 0是支出,1是收入
//            tv_money_num.setText(flowType + flow.getMoney());// 1是支出,0是收入
            //2020-11-29 改为由后台返回
//            String flowType = TextUtils.equals("0", flow.getPay_type()) ? "-" : "+";// 0是支出,1是收入
            tv_money_num.setText(flow.getMoney());// 1是支出,0是收入
        }
    }
}